<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class IntegralRecord extends Model
{
    use SoftDeletes;
    protected $table = 'integral_records';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];


    /**
     * 积分记录保存
     * @param array $recordData
     * $recordData = [
        'integral_num' => '',
        'types' => '',
        'obj_id' => '',
        'explain' => '',
        'user_id' => '',
        'obj_source' => '',
        ];
     * @return bool
     */
    public static function store($recordData = [])
    {
        $user = User::find($recordData['user_id']);

        if ($recordData['types'] == 2) {
            $user->integral_num -= $recordData['integral_num'];
        } else {
            $user->integral_num += $recordData['integral_num'];
        }

        if ($user->integral_num < 0) {
            return false;
        }
        $save_user_res = $user->save();

        $recordData['integral_num_after'] = $user->integral_num;
        $save_record_res = self::create($recordData);

        if ($save_user_res && $save_record_res) {
            return true;
        } else {
            return false;
        }
    }
}
